package com.usermanage.ServiceImpl;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.ConfirmCallback;
import com.usermanage.Mapping.MessageMapping;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.CompanyService;
import com.usermanage.Service.MessageService;
import com.usermanage.Service.UserCenterService;
import com.usermanage.Service.UserService;
import com.usermanage.beanParam.CompanyBean;
import com.usermanage.beanParam.MessageBean;
import com.usermanage.beanParam.UserBean;
import com.usermanage.beanParam.UserCenterBean;
import com.usermanage.dataDao.JpaDao;
import com.usermanage.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Service("rabbitMQService")
public class MessageServiceImpl implements MessageService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Resource
    private MessageMapping messageMapping;

    @Resource
    private UserService userService;

    @Resource
    private CompanyService companyService;

    @Resource
    private UserCenterService userCenterService;
    @Resource
    private JpaDao jpaDao;


    //    final ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback(){
//
//        @Override
//        public void confirm(CorrelationData correlationData, boolean b, String s) {
//            System.out.println("correlationData:"+correlationData);
//            String messageId = correlationData.getId();
//            if(b){
//            }else{
//
//            }
//        }
//    }
    @Override
    public void send(MessageBean messageBean) throws Exception {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        log.info("当前登录用户信息" + StringUtil.ObjectToJson(userDetail));
//        List<UserBean> userBeans = userService.getAllUserList();
        messageBean.setMessage_code(StringUtil.getMessageCode());
        messageBean.setMessage_create_date(new Date());
//        if ("msg010".equals(messageBean.getMessage_type()) || "msg011".equals(messageBean.getMessage_type())) {
//            messageBean.setMessage_creater(String.valueOf(userDetail.getId()));
//            StringBuffer buffer = new StringBuffer();
//            for (UserBean userBean : userBeans) {
//                buffer.append(userBean.getId()).append(",");
//            }
//            messageBean.setMessage_sendee(buffer.toString());
//            messageBean.setMessage_no(messageBean.getMessage_body());
//        }
        String senddList = messageBean.getMessage_sendee();
        String[] createrList = senddList.split(",");
        for (int i = 0; i < createrList.length; i++) {
//            if (createrList[i].equals(messageBean.getMessage_creater())) {
//                if ("msg005".equals(messageBean.getMessage_type())) {
//                    messageBean.setMessage_status("99");
//                    List<MessageBean> list = this.findSendee(null, null, messageBean.getMessage_no(), null, messageBean.getMessage_creater(), "msg003", null);
//                    if (list.size() > 0) {
//                        messageBean.setMessage_creater(list.get(0).getMessage_creater());
//                    }
//                    rabbitTemplate.convertAndSend("EOS-exchange", "EOS-message", messageBean);
//                    messageBean.setMessage_type("msg002");
//                    messageBean.setMessage_sendee(list.get(0).getMessage_creater());
//                    rabbitTemplate.convertAndSend("EOS-exchange", "EOS-message", messageBean);
//                }else{
            messageBean.setMessage_sendee(createrList[i]);
            messageBean.setMessage_status("99");
            rabbitTemplate.convertAndSend("EOS-exchange", "EOS-message", messageBean);
//                }
//            } else {
//                messageBean.setMessage_sendee(createrList[i]);
//                messageBean.setMessage_status("99");
//                rabbitTemplate.convertAndSend("EOS-exchange", "EOS-message", messageBean);
//            }
        }
    }


//    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "msg_Queque", durable = "true"), exchange = @Exchange(name = "msgChange", durable = "true", type = "direct"), key = "msgRouteKey"))
//    @RabbitHandler
//    public void get(@Payload String param, @Headers Map<String, Object> headers, Channel channel) throws Exception {
//        log.info("消息接收成功" + param);
//        Map message = StringUtil.JsonToMap(param);
////        insert(String.valueOf(message.get("message_sendee")), "49", StringUtil.ObjectToJson(message.get("message_body")), new Date(), StringUtil.ObjectToJson(message.get("message_type")), StaticUtil.company);
//        MessageBean messageBean = new MessageBean();
//        messageBean.setMessage_code(StringUtil.getMessageCode());
//        messageBean.setMessage_sendee(String.valueOf(message.get("message_sendee")));
//        messageBean.setMessage_body(StringUtil.ObjectToJson(message.get("message_body")));
//        messageBean.setMessage_create_date(new Date());
//        messageBean.setMessage_type(StringUtil.ObjectToJson(message.get("message_type")));
//        messageBean.setMessage_status("99");
//        insert(messageBean);
//        log.info("消息保存成功" + param);
//        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
//        channel.basicAck(deliveryTag, false);
    @RabbitListener(bindings = @QueueBinding(value = @Queue(value = "EOS-queue", durable = "true"), exchange = @Exchange(name = "EOS-exchange", durable = "true", type = "direct"), key = "EOS-message"))
    @RabbitHandler
    public void get(@Payload MessageBean messageBean, @Headers Map<String, Object> headers, Channel channel) throws Exception {
        log.info("消息接收成功" + StringUtil.ObjectToJson(messageBean));
        messageMapping.save(messageBean);
        log.info("消息消费成功" + StringUtil.ObjectToJson(messageBean));
        dingSend(messageBean);
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);
    }

    @Override
    public void dingSend(MessageBean messageBean) throws Exception {
        log.info("进入钉钉消息推送接口");
        Optional<UserCenterBean> userCenterBean = userCenterService.findById(Integer.valueOf(messageBean.getMessage_sendee()));
        if (userCenterBean.get().isUser_notify() && StringUtils.isNotBlank(userCenterBean.get().getUser_ding_id())) {
            log.info("=====================开始钉钉消息推送内容解析=====================");
            UserBean userBean = userService.findUserDetail(messageBean.getMessage_creater());
            Optional<CompanyBean> optional = companyService.findById(Integer.valueOf(userBean.getCompany_id()));
            messageBean.setCreater_company(optional.get().getCompany_name());
            messageBean.setMessage_creater(userBean.getUser_name());
//            messageBean.setCreater_dept(userBean.getUser_dept());
            String dingText = "";
            String messageBody = messageBean.getMessage_body();
            log.info("开始钉钉消息推送内容：" + messageBody);
//            if ("msg001".equals(messageBean.getMessage_type())) {
                dingText = messageBody;
//                dingText = messageBean.getCreater_company() + "  " + messageBean.getMessage_creater() + "  于  " + DateUtil.formatDateByDate(messageBean.getMessage_create_date()) + "  下了一笔采购订单,编号为  " + messageBean.getMessage_no() + "  ,请确认清单。";
//            } else if ("msg002".equals(messageBean.getMessage_type())) {
//                dingText = messageBody;
////                dingText = "编号为  " + messageBean.getMessage_no() + "  发货单已出库,请及时跟踪。";
//            } else if ("msg003".equals(messageBean.getMessage_type())) {
//                dingText = messageBody;
////                dingText = messageBean.getCreater_company() + "  的  " + messageBean.getMessage_creater() + "  确认了销售订单，编号为  " + messageBean.getMessage_no() + "  ,请确认订单是否有误。";
//            } else if ("msg004".equals(messageBean.getMessage_type())) {
//                dingText = messageBody;
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getMessage_creater() + "  于  " + DateUtil.formatDateByDate(messageBean.getMessage_create_date()) + "  确认了采购订单，编号为  " + messageBean.getMessage_no() + "  的采购订单,请及时查看并安排出库。";
//            } else if ("msg005".equals(messageBean.getMessage_type())) {
//                dingText = messageBody;
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getCreater_dept() + "  " + messageBean.getMessage_creater() + "  完成了编号为  " + messageBean.getMessage_no() + "  发货单的出库,请及时跟踪。";
//            } else if ("msg006".equals(messageBean.getMessage_type())) {
//                dingText = messageBody;
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getCreater_dept() + "  " + messageBean.getMessage_creater() + "  于  " + DateUtil.formatDateByDate(messageBean.getMessage_create_date()) + "  完成了编号为  " + messageBean.getMessage_no() + "  收货单的收货处理,请及时查看。";
////            } else if ("msg007".equals(messageBean.getMessage_type())) {
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getMessage_creater() + "  提交了订单编号为  " + messageBean.getMessage_no() + "  的付款,请及时确认。";
////            } else if ("msg008".equals(messageBean.getMessage_type())) {
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getMessage_creater() + "  拒绝了订单编号为  " + messageBean.getMessage_no() + "  的付款，请及时查看。";
////            } else if ("msg009".equals(messageBean.getMessage_type())) {
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getMessage_creater() + "  确认了订单编号为  " + messageBean.getMessage_no() + "  的付款，请及时查看。";
//            } else if ("msg008".equals(messageBean.getMessage_type())) {
//                dingText = messageBody;
////                Map SKU = StringUtil.JsonToMap(messageBean.getMessage_body());
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getMessage_creater() + "  新增了一条SKU，名称为  " + SKU.get("sku_name") + "  ，编号为  " + messageBean.getMessage_no() + "  ，请及时查看。";
////            } else if ("msg011".equals(messageBean.getMessage_type())) {
////                Map SPU = StringUtil.JsonToMap(messageBean.getMessage_body());
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getMessage_creater() + "  下架了一条SPU，名称为  " + SPU.get("spu_name") + "  ，编号为  " + messageBean.getMessage_no() + "  ，请及时查看。";
////            } else if ("msg012".equals(messageBean.getMessage_type())) {
////                dingText = messageBean.getMessage_body();
////            } else if ("msg013".equals(messageBean.getMessage_type())) {
////                dingText = messageBean.getCreater_company() + "  " + messageBean.getMessage_creater() + "  下了一笔新订单,订单编号为  " + messageBean.getMessage_no() + "  ,请及时确认。";
//            } else {
//                dingText = "您有新的未读消息，请登录EOS查看。";
//            }
            Map param = new HashMap();
            param.put("userid_list", userCenterBean.get().getUser_ding_id());
            param.put("msg", dingText);
            log.info("=====================开始钉钉消息推送=====================");
            String result = HttpUtil.post(StaticUtil.ORDERIP + "/Order/dingMsgController/pushDingMsg.json", StringUtil.ObjectToJson(param));
            log.info("结束钉钉消息推送======================推送结果：" + result);
        } else {
            log.info("接收人未开启钉钉推送，该消息不推送");
        }
    }

    /**
     * 分页得到通知信息
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<MessageBean> getAllList(String sendee, String page, String size) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT * FROM  u_message where message_sendee = '").append(sendee).append("'");
        buffer.append(" order by message_status desc,message_create_date desc limit ").append((Integer.valueOf(page) - 1) * Integer.valueOf(size)).append(",").append(size);
        List<MessageBean> list = jpaDao.getListByPage(buffer.toString(),MessageBean.class);
        return list;
    }

    /**
     * 分页得到通知信息记录数
     *
     * @return
     */
    @Override
    public int getAllListCount(String sendee) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT count(*) FROM  u_message where message_sendee = '").append(sendee).append("'");
        return jpaDao.getListCountByPage(buffer.toString());
    }

    @Override
    public void insert(MessageBean messageBean) {
        try {
            messageMapping.save(messageBean);
            log.info("消息保存成功");
        } catch (Exception e) {
            log.error(e.toString());
        }

    }

    @Override
    public JsonData updateRead(String message_code) {
        try {
            StringBuffer buffer = new StringBuffer();
            buffer.append("SELECT * FROM  u_message where message_code = '").append(message_code).append("'");
            List<MessageBean> list = jpaDao.getListByPage(buffer.toString(),MessageBean.class);
            for (MessageBean bean : list) {
                bean.setMessage_status("00");
                messageMapping.save(bean);
            }
            return JsonData.success();
        } catch (Exception e) {
            return JsonData.fail(e.toString());
        }
    }

    @Override
    public List<Map> findSendeeUesrList(String company_id, String permission_id) {
        return messageMapping.findSendeeUesrList(company_id, permission_id);
    }

    @Override
    public int userUnReadCount(String sendee) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT count(*) FROM  u_message where message_sendee = '").append(sendee).append("'");
        buffer.append(" and message_status = '99'");
        return jpaDao.getListCountByPage(buffer.toString());
    }

    @Override
    public List<MessageBean> findSendee(String id, String message_code, String message_no, String message_creater, String message_sendee, String message_type, String message_status) {

        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT * FROM  u_message where 1 =1 ");
        if (StringUtils.isNotBlank(id)) {
            buffer.append(" and id = '").append(id).append("' ");
        }
        if (StringUtils.isNotBlank(message_code)) {
            buffer.append(" and message_code = '").append(message_code).append("' ");
        }
        if (StringUtils.isNotBlank(message_no)) {
            buffer.append(" and message_no = '").append(message_no).append("' ");
        }
        if (StringUtils.isNotBlank(message_creater)) {
            buffer.append(" and message_creater = '").append(message_creater).append("' ");
        }
        if (StringUtils.isNotBlank(message_sendee)) {
            buffer.append(" and message_sendee = '").append(message_sendee).append("' ");
        }
        if (StringUtils.isNotBlank(message_type)) {
            buffer.append(" and message_type = '").append(message_type).append("' ");
        }
        if (StringUtils.isNotBlank(message_status)) {
            buffer.append(" and message_status = '").append(message_status).append("' ");
        }
        List<MessageBean> list = jpaDao.getListByPage(buffer.toString(),MessageBean.class);
        return list;
    }

    @Override
    public void rabbitMq(String exchange, String routingkey, String msg) {

        rabbitTemplate.convertAndSend(exchange, routingkey, msg);

    }

    public void demo(MessageBean messageBean) {

        String[] sendeeList = messageBean.getMessage_sendee().split(",");
        for (int i = 0; i < sendeeList.length; i++) {
//            sendeeList[i];
        }


    }
}
